package dao;

import java.util.ArrayList;
import java.util.List;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import static org.hibernate.criterion.Example.create;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A data access object (DAO) providing persistence and search support for
 * Chatmessage entities. Transaction control of the save(), update() and
 * delete() operations can directly support Spring container-managed
 * transactions or they can be augmented to handle user-managed Spring
 * transactions. Each of these methods provides additional information for how
 * to configure it for the desired type of transaction control.
 * 
 * @see dao.Chatmessage
 * @author MyEclipse Persistence Tools
 */

public class ChatmessageDAO extends BaseHibernateDAO {
    private static final Logger log = LoggerFactory
	    .getLogger(ChatmessageDAO.class);
    // property constants
    public static final String SOURCE = "source";
    public static final String DESTINATION = "destination";
    public static final String MESSAGE = "message";
    public static final String READFLAG = "readflag";

    public boolean save(Chatmessage transientInstance) {
	return save(log, "saving Chatmessage instance", transientInstance);
    }

    public boolean delete(Chatmessage persistentInstance) {
	return delete(log, "deleting Chatmessage instance", persistentInstance);
    }

    public Chatmessage findById(java.lang.Integer id) {
	log.debug("getting Chatmessage instance with id: " + id);
	try {
	    Chatmessage instance = (Chatmessage) getSession().get(
		    "dao.Chatmessage", id);
	    return instance;
	} catch (RuntimeException re) {
	    log.error("get failed", re);
	    throw re;
	}
    }

    public List<Chatmessage> findByExample(Chatmessage instance) {
	log.debug("finding Chatmessage instance by example");
	try {
	    List<Chatmessage> results = (List<Chatmessage>) getSession()
		    .createCriteria("dao.Chatmessage").add(create(instance))
		    .list();
	    log.debug("find by example successful, result size: "
		    + results.size());
	    return results;
	} catch (RuntimeException re) {
	    log.error("find by example failed", re);
	    throw re;
	}
    }

    public List<Chatmessage> findByProperty(String propertyName, Object value) {
	log.debug("finding Chatmessage instance with property: " + propertyName
		+ ", value: " + value);
	try {
	    String queryString = "from Chatmessage as model where model."
		    + propertyName + "= ?";
	    Query queryObject = getSession().createQuery(queryString);
	    queryObject.setParameter(0, value);
	    return queryObject.list();
	} catch (RuntimeException re) {
	    log.error("find by property name failed", re);
	    throw re;
	}
    }

    public List<Chatmessage> findBySource(Object source) {
	return findByProperty(SOURCE, source);
    }

    public List<Chatmessage> findByDestination(Object destination) {
	return findByProperty(DESTINATION, destination);
    }

    public List<Chatmessage> findByMessage(Object message) {
	return findByProperty(MESSAGE, message);
    }

    public List<Chatmessage> findByReadflag(Object readflag) {
	return findByProperty(READFLAG, readflag);
    }

    public List<Chatmessage> findUnreadBySource(String source, String flag) {
	log.debug("getting unread Chatmessag with source: " + source);
	try {
	    String hqlString = "from Chatmessage where source=? and readflag='0'";
	    if (flag.equals("readed")) {
		hqlString = "from Chatmessage where source=? and readflag='1'";
	    }
	    Query query = getSession().createQuery(hqlString);
	    query.setString(0, source);
	    List<Chatmessage> list = query.list();
	    return list;
	} catch (RuntimeException re) {
	    log.error("get failed", re);
	    throw re;
	}
    }

    public List findAll() {
	log.debug("finding all Chatmessage instances");
	try {
	    String queryString = "from Chatmessage";
	    Query queryObject = getSession().createQuery(queryString);
	    return queryObject.list();
	} catch (RuntimeException re) {
	    log.error("find all failed", re);
	    throw re;
	}
    }

    public List<Chatmessage> findDes(String desId, String flag) {
	try {
	    String queryString = "from Chatmessage where destination=? and readflag=?";
	    Query queryObject = getSession().createQuery(queryString);
	    queryObject.setString(0, desId);
	    queryObject.setString(1, flag);
	    return queryObject.list();
	} catch (RuntimeException re) {
	    throw re;
	}
    }

    public List<Chatmessage> findSource(String desId, String flag) {
	try {
	    String queryString = "from Chatmessage where source=? and readflag=?";
	    Query queryObject = getSession().createQuery(queryString);
	    queryObject.setString(0, desId);
	    queryObject.setString(1, flag);
	    return queryObject.list();
	} catch (RuntimeException re) {
	    throw re;
	}
    }
    
    public int getDesCounts(String id) {
	try {
	    String queryString = "select count(messageid) from Chatmessage where destination=? and readflag='0'";
	    Query queryObject = getSession().createQuery(queryString);
	    queryObject.setString(0, id);
	    return ((Number) queryObject.uniqueResult()).intValue();// Long向上转换为Number,再转换为Integer
	} catch (RuntimeException re) {
	    throw re;
	}
    }

    public int getSourceCounts(String id) {
	try {
	    String queryString = "select count(messageid) from Chatmessage where source=? and readflag='0'";
	    Query queryObject = getSession().createQuery(queryString);
	    queryObject.setString(0, id);
	    return ((Number) queryObject.uniqueResult()).intValue();// Long向上转换为Number,再转换为Integer
	} catch (RuntimeException re) {
	    throw re;
	}
    }
    public List<Chatmessage> findMessageByids(List<Integer> idList) {
	try {
	    if (idList.size() > 0) {
		StringBuilder queryString = new StringBuilder(
			"from Chatmessage where messageid in(");
		for (int id : idList) {
		    queryString.append(id).append(",");
		}
		queryString.replace(queryString.length() - 1,
			queryString.length(), ")");
		Query queryObject = getSession().createQuery(
			queryString.toString());
		return queryObject.list();
	    } else {
		return null;
	    }
	} catch (RuntimeException re) {
	    throw re;
	}
    }

    public Chatmessage merge(Chatmessage detachedInstance) {
	log.debug("merging Chatmessage instance");
	try {
	    Chatmessage result = (Chatmessage) getSession().merge(
		    detachedInstance);
	    log.debug("merge successful");
	    return result;
	} catch (RuntimeException re) {
	    log.error("merge failed", re);
	    throw re;
	}
    }

    public boolean saveReply(Chatmessage message, int id) {
	Session session = getSession();
	Transaction transaction = session.beginTransaction();
	try {	    
	    session.save(message);
	    String queryString = "update Chatmessage set readflag ='1', replyid=? where messageid=?";
	    Query queryObject = session.createQuery(queryString);
	    queryObject.setInteger(0, message.getMessageid());
	    queryObject.setInteger(1, id);
	    queryObject.executeUpdate();
	    transaction.commit();
	    session.flush();
	    session.close();
	    return true;
	} catch (RuntimeException re) {
	    transaction.rollback();
	    throw re;
	}
    }

    public boolean update(Chatmessage instance) {
	return update(log, "updating Chatmessage instance", instance);
    }

    public void attachClean(Chatmessage instance) {
	log.debug("attaching clean Chatmessage instance");
	try {
	    getSession().lock(instance, LockMode.NONE);
	    log.debug("attach successful");
	} catch (RuntimeException re) {
	    log.error("attach failed", re);
	    throw re;
	}
    }
    public static void main(String[] args){
	ChatmessageDAO chatmessageDAO = new ChatmessageDAO();
	List<Integer> list = new ArrayList<Integer>();
	list.add(4);
	List<Chatmessage> list2 = chatmessageDAO.findMessageByids(list);
	System.out.println(list2.get(0).getSendtime());
    }
}